package com.example.startscreen;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.text.method.LinkMovementMethod;
import android.util.Log;

public class OnlineMapActivity extends MapActivity {

	static enum mapmodeEnum {
		DRAW_ALL_MUNICIPALS(1), DRAW_CATEGORY_FOR_ONE_MUNICIPAL(2), DRAW_CATEGORY_FOR_ALL_MUNICIPALS(
				3);

		private int value;

		private mapmodeEnum(int value) {
			this.value = value;
		}

		public int getValue() {
			return value;
		}
	}

	static enum reqCodeEnum {
		POPUP_LIST_CATEGORIES_FOR_ALL_MUNICIPALS(1), POPUP_LIST_CATEGORIES_FOR_ONE_MUNICIPAL(
				2), REQUEST_CODE_LOCINFO(3);

		private int value;

		private reqCodeEnum(int value) {
			this.value = value;
		}

		public int getValue() {
			return value;
		}
	}

	final Context context = this;

	public static int drawMode = OnlineMapActivity.mapmodeEnum.DRAW_ALL_MUNICIPALS
			.getValue();

	public static int locId = 0;
	public static int catId = 0; // 0: iscrtaj sve opstine, 1-n: iscrtaj samo
									// datu kategoriju
	public static int cityId = 0; // 0: iscrtaj sve opstine, 1-n: iscrtaj samo
									// datu opstinu

	LocationManager locMgr;

	public GeoPoint curPoint; // point of currently tapp-ed overlay item

	// MyLocationListener locLstnr;
	public ArrayList<MapLocation> mapLocationArr = new ArrayList<MapLocation>();

	int minLat = Integer.MAX_VALUE;
	int maxLat = Integer.MIN_VALUE;
	int minLon = Integer.MAX_VALUE;
	int maxLon = Integer.MIN_VALUE;

	int overlayTitleSize = 15; // size of mapview item text title

	/*
	 * umjesto MapView klase, uveli smo nasu klasu MyCustomMapView, u kojoj smo
	 * implementirali jednu vrstu OnLongClick!!! private MapView mapView;
	 */
	private MyCustomMapView mapView;
	private MapController mc;

	MyLocationListener locLstnr;
	String pg_lat = "42.44138438986998", pg_long = "19.262638092041015";
	private Location locPodgorica = new Location("gps");
	private Location currGpsLocation = new Location("gps");
	private boolean askedToActivateGps = false;
	private boolean gpsProviderEnabled = false;
	// MontenegroCityPolygons mcp = new MontenegroCityPolygons();
	MyMontenegroCityPolygons mcp = new MyMontenegroCityPolygons();

	private boolean askedToActivateInternet = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.onlinemap); // ovo ukazuje na onlinemap.xml!!!
		// mapView = (MapView) findViewById(R.id.online_map_view);
		// ovo sam definisao u onlinemap.xml!!!
		mapView = (MyCustomMapView) findViewById(R.id.online_map_view);
		mc = mapView.getController();
		mapView.setBuiltInZoomControls(true);

		// create montenegro city polygins
		// mcp.generatePolygons();

		// check for internet connection (should be done more preciously, with
		// access to some host on internet!!!)
		if (!askedToActivateInternet) {
			askedToActivateInternet = true;
			if (!isOnline()) {
				Toast.makeText(this, getString(R.string.missing_internet),
						Toast.LENGTH_LONG).show();
			}
		}
		// setup current GPS location (some referent point in case that GPS is
		// not activated)
		locPodgorica.setLatitude(Double.parseDouble(pg_lat));
		locPodgorica.setLongitude(Double.parseDouble(pg_long));
		currGpsLocation.setLatitude(Double.parseDouble(pg_lat));
		currGpsLocation.setLongitude(Double.parseDouble(pg_long));

		locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		gpsProviderEnabled = locMgr
				.isProviderEnabled(LocationManager.GPS_PROVIDER);

		// Check if GPS is enabled and if not display a dialog and suggesting to
		// go to the settings
		if (gpsProviderEnabled) {
			Toast.makeText(this, getString(R.string.gps_enabled),
					Toast.LENGTH_LONG).show();
		} else {
			if (!askedToActivateGps) {
				askedToActivateGps = true;
				showGPSDisabledAlertToUser();
			}
		}

		// activate GPS listeneronly if GPS provider is enabled
		// enabled = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
		// if (gpsProviderEnabled) {
		locLstnr = new MyLocationListener();
		locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000,
				100, locLstnr); // each 2 minutes, with movement of at least 100
								// meters!!!
		// }

		mapView.setOnLongpressListener(new MyCustomMapView.OnLongpressListener() {
			public void onLongpress(final MapView view,
					final GeoPoint longpressLocation) {
				runOnUiThread(new Runnable() {
					public void run() {
						// Insert your longpress action here
						// Log.i("OnLineMapActiviy - OnLongpressListener",
						// "EEEEEEEEEEEEE");
						handleLongressListener(longpressLocation);
					}
				});
			}
		});

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			drawMode = extras.getInt("whatToDo");
			Log.i("OnCreate Extra_GetInt - drawMode: ", "" + drawMode);
			if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ONE_MUNICIPAL
					.getValue()) {
				catId = extras.getInt("catID");
				cityId = extras.getInt("cityID");
				Log.i("OnCreate Extra_GetInt - catID: ", "" + catId);
				Log.i("OnCreate Extra_GetInt - cityID: ", "" + cityId);
			} else if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ALL_MUNICIPALS
					.getValue()) {
				catId = extras.getInt("catID");
				cityId = extras.getInt("cityID");
				Log.i("OnCreate Extra_GetInt - catID: ", "" + catId);
				Log.i("OnCreate Extra_GetInt - cityID: ", "" + cityId);
			}
		}

		// decide what to draw
		if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_ALL_MUNICIPALS
				.getValue()) {
			drawMunicipals();
		} else if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ONE_MUNICIPAL
				.getValue()) {
			drawCategoryForOneMunicipal(catId, cityId);
		} else if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ALL_MUNICIPALS
				.getValue()) {
			drawCategoryForMunicipals(catId, cityId);
		}
	}

	private void showGPSDisabledAlertToUser() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder
				.setMessage(getString(R.string.gps_disabled))
				.setCancelable(false)
				.setPositiveButton(
						getString(R.string.gps_dialog_positive_button),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								Intent callGPSSettingIntent = new Intent(
										android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								startActivity(callGPSSettingIntent);
							}
						});
		alertDialogBuilder.setNegativeButton(
				getString(R.string.gps_dialog_negative_button),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = alertDialogBuilder.create();
		alert.show();
	}

	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnected()) {
			return true;
		}
		return false;
	}

	@Override
	public void onBackPressed() {
		if (drawMode != OnlineMapActivity.mapmodeEnum.DRAW_ALL_MUNICIPALS
				.getValue()) {
			drawMunicipals();
			return;
		}
		// TODO Auto-generated method stub
		super.onBackPressed();
	}

	// Initiating Menu XML file (onlinemap_menu.xml)
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		// return super.onCreateOptionsMenu(menu);
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.onlinemap_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		// return super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.popup_category:
			this.pickupCategory();
			return true;

		case R.id.popup_municipal:
			this.pickupMunicipal();
			return true;

		case R.id.mapview_normal:
			if (mapView.isSatellite() == true) {
				mapView.setSatellite(false);
			}
			return true;

		case R.id.mapview_satellite:
			if (mapView.isSatellite() == false) {
				mapView.setSatellite(true);
			}
			return true;

		case R.id.my_location:
			ZoomToCurrentLocation();
			Toast.makeText(this,
					getString(R.string.current_location_change_note),
					Toast.LENGTH_LONG).show();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/*
	 * Display all municipals as simple markers
	 */
	public boolean drawMunicipals() {

		// set mode flag (this might be obsolete in future releases!!!
		drawMode = OnlineMapActivity.mapmodeEnum.DRAW_ALL_MUNICIPALS.getValue();

		// Don't forget to clear mapLocationArr, before all other tasks!!!
		mapLocationArr.clear();

		Municipal opstina;
		for (int i = 0; i < Municipal.arrMunicipal.length; i++) {
			opstina = Municipal.arrMunicipal[i];
			MapLocation mapLocation = new MapLocation(opstina.locID,
					opstina.catID, opstina.cityID, opstina.ime, opstina.name,
					opstina.latlongpair, opstina.description);
			// Log.i("Adding map location", opstina.name);
			mapLocationArr.add(mapLocation);
		}

		// display overlay items
		return prepareOverlayItemsForMunicipals();
	}

	protected boolean prepareOverlayItemsForMunicipals() {
		// reset bounding rectangle of the displayed map
		minLat = Integer.MAX_VALUE;
		maxLat = Integer.MIN_VALUE;
		minLon = Integer.MAX_VALUE;
		maxLon = Integer.MIN_VALUE;

		List<Overlay> mapOverlays = mapView.getOverlays();
		// DONT FORGET TO CLEAR OVERLAY ARRAY FIRST!!!
		mapOverlays.clear();
		Drawable drawable = this.getResources()
				.getDrawable(R.drawable.marker_c);
		CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
				drawable, this, overlayTitleSize);

		// kreiraj overlay items za date tacke
		Iterator<MapLocation> locIt = this.mapLocationArr.iterator();
		int index = 0;
		while (locIt.hasNext()) {
			MapLocation loc = (MapLocation) locIt.next();
			MyOverlayItem overlayitem = new MyOverlayItem(loc.locID, loc.catID,
					loc.cityID, loc.point, loc.name, loc.name);
			itemizedOverlay.addOverlay(overlayitem);
			// calculate bounding rectangle
			int lat = loc.point.getLatitudeE6();
			int lon = loc.point.getLongitudeE6();
			maxLat = Math.max(lat, maxLat);
			minLat = Math.min(lat, minLat);
			maxLon = Math.max(lon, maxLon);
			minLon = Math.min(lon, minLon);

			index++;
		}

		// dodaj ove overlay item-e u mapOverlays
		mapOverlays.add(itemizedOverlay);

		// prikazi bounding rectangle svih markiranih pointa
		double fitFactor = 1.10;
		mapView.getController().zoomToSpan(
				(int) (Math.abs(maxLat - minLat) * fitFactor),
				(int) (Math.abs(maxLon - minLon) * fitFactor));
		mapView.getController().animateTo(
				new GeoPoint((maxLat + minLat) / 2, (maxLon + minLon) / 2));
		mapView.invalidate();

		return true;
	}

	/*
	 * Display category for all or only one municipal. catID = 0: ERROR! catID
	 * != 0: draw category
	 */
	public boolean drawCategoryForMunicipals(int catID, int cityID) {
		// If catID is zero, it must be error. Calling f() should take care
		// not to happen. Return without drawing anything!!!
		if (catID == 0)
			return false;

		catId = catID;
		drawMode = OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ALL_MUNICIPALS
				.getValue();
		return drawCategory(catID, cityID);
	}

	/*
	 * Display one or all categories for only one municipal cityID = 0: ERROR!
	 * cityID != 0: draw category
	 */
	public boolean drawCategoryForOneMunicipal(int catID, int cityID) {
		if (cityID == 0)
			return false;

		// save global cityId, as OnActivityResult need that to call propper f()
		// after calling popup list
		cityId = cityID;
		catId = catID;
		drawMode = OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ONE_MUNICIPAL
				.getValue();
		return drawCategory(catID, cityID);
	}

	protected boolean drawCategory(int catID, int cityID) {

		// Don't forget to clear mapLocationArr, before all other tasks!!!
		mapLocationArr.clear();

		if (catID == 0 || catID == Category.categoryEnum.HISTORY.getValue()) {
			HistoryLocation location;
			for (int i = 0; i < HistoryLocation.arrHistory.length; i++) {
				location = HistoryLocation.arrHistory[i];
				if (cityID == 0 || cityID == location.cityID) {
					Log.i("displayMunicipal", "History, locID: "
							+ location.locID + ", catID: " + location.catID
							+ ", cityID: " + location.cityID);
					MapLocation mapLocation = new MapLocation(location.locID,
							location.catID, location.cityID, location.ime,
							location.name, location.latlongpair,
							location.description);
					mapLocationArr.add(mapLocation);
				}
			}
		}
		// if (Category.categoryEnum.valueOf(catID) ==
		// Category.categoryEnum.NATURE) { // draw nature objects
		if (catID == 0 || catID == Category.categoryEnum.NATURE.getValue()) {
			NatureLocation location;
			for (int i = 0; i < NatureLocation.arrNature.length; i++) {
				location = NatureLocation.arrNature[i];
				if (cityID == 0 || cityID == location.cityID) {
					Log.i("displayMunicipal", "Nature, locID: "
							+ location.locID + ", catID: " + location.catID
							+ ", cityID: " + location.cityID);
					MapLocation mapLocation = new MapLocation(location.locID,
							location.catID, location.cityID, location.ime,
							location.name, location.latlongpair,
							location.description);
					mapLocationArr.add(mapLocation);
				}
			}
		}

		if (catID == 0 || catID == Category.categoryEnum.ARCHEOLOGY.getValue()) { // draw
																					// archeology
																					// objects
			ArcheologyLocation location;
			for (int i = 0; i < ArcheologyLocation.arrArcheology.length; i++) {
				location = ArcheologyLocation.arrArcheology[i];
				if (cityID == 0 || cityID == location.cityID) {
					Log.i("displayMunicipal", "Archeology, locID: "
							+ location.locID + ", catID: " + location.catID
							+ ", cityID: " + location.cityID);
					MapLocation mapLocation = new MapLocation(location.locID,
							location.catID, location.cityID, location.ime,
							location.name, location.latlongpair,
							location.description);
					mapLocationArr.add(mapLocation);
				}
			}
		}

		// add municipal(s) at the end (I hope, they will be visible then)
		Municipal opstina;
		for (int i = 0; i < Municipal.arrMunicipal.length; i++) {
			opstina = Municipal.arrMunicipal[i];
			if (cityID == 0 || cityID == opstina.cityID) {
				MapLocation mapLocation = new MapLocation(opstina.locID,
						opstina.catID, opstina.cityID, opstina.ime,
						opstina.name, opstina.latlongpair, opstina.description);
				mapLocationArr.add(mapLocation);
			}
		}

		// display overlay items
		return prepareOverlayItems();
	}

	protected boolean prepareOverlayItems() {

		// reset bounding rectangle of the displayed map
		minLat = Integer.MAX_VALUE;
		maxLat = Integer.MIN_VALUE;
		minLon = Integer.MAX_VALUE;
		maxLon = Integer.MIN_VALUE;

		List<Overlay> mapOverlays = mapView.getOverlays();

		// DONT FORGET TO CLEAR OVERLAY ARRAY FIRST!!!
		mapOverlays.clear();
		Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
		CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
				drawable, this, overlayTitleSize);

		/*
		 * Napomena: da bi se prikazao default drawable za overlay item dovoljan
		 * je osnovni konstruktor. Ali, kada se zeli mijenjati ikona (drawable)
		 * onda dokumentacija nije bas precizna. Za korektno podesavanje
		 * pozicije i uopste iscrtavanje, treba pozvati setBounds, ali tu onda
		 * treba voditi racuna, gdje ce doci tacka koja se zeli smatrati onom
		 * koja ukazuje na stvarnu GeoPoint. U sledecem primjeru, mi imamo ikonu
		 * marker (raznih boja) a njena donja srednja lokacija je ona tacka koja
		 * treba da ukazuje na stvarnu lokaciju na mapi, pa smo morali malo da
		 * podesavamo setBounds!!!
		 */
		Drawable icon = getResources().getDrawable(R.drawable.marker_green);
		Iterator<MapLocation> locIt = this.mapLocationArr.iterator();
		int index = 0;
		while (locIt.hasNext()) {

			MapLocation loc = (MapLocation) locIt.next();
			if (loc.catID == Category.categoryEnum.HISTORY.getValue()) {
				icon = getResources().getDrawable(R.drawable.historicalquarter);
			} else if (loc.catID == Category.categoryEnum.NATURE.getValue()) {
				icon = getResources().getDrawable(R.drawable.beautifulview);
			} else if (loc.catID == Category.categoryEnum.ARCHEOLOGY.getValue()) {
				icon = getResources().getDrawable(R.drawable.monument);
			} else if (loc.catID == 0) { // this is municipal
				icon = getResources().getDrawable(R.drawable.marker_c);
			} else {
				icon = getResources().getDrawable(R.drawable.small_red_marker);
			}

			icon.setBounds(-icon.getIntrinsicWidth() / 2,
					-icon.getIntrinsicHeight(), icon.getIntrinsicWidth() / 2, 0);
			MyOverlayItem overlayitem;
			if (MainActivity.language == MainActivity.languageEnum.MONTENEGRO
					.getValue())
				overlayitem = new MyOverlayItem(loc.locID, loc.catID,
						loc.cityID, loc.point, loc.ime, loc.name);
			else
				overlayitem = new MyOverlayItem(loc.locID, loc.catID,
						loc.cityID, loc.point, loc.name, loc.name);
			overlayitem.setMarker(icon); // this is where we setup non-default
											// drawable
			itemizedOverlay.addOverlay(overlayitem);

			// calculate bounding rectangle
			int lat = loc.point.getLatitudeE6();
			int lon = loc.point.getLongitudeE6();
			maxLat = Math.max(lat, maxLat);
			minLat = Math.min(lat, minLat);
			maxLon = Math.max(lon, maxLon);
			minLon = Math.min(lon, minLon);

			index++;

		}

		// add overlay items into mapOverlays
		mapOverlays.add(itemizedOverlay);

		// make sure all items will be visible
		double fitFactor = 1.10;
		mapView.getController().zoomToSpan(
				(int) (Math.abs(maxLat - minLat) * fitFactor),
				(int) (Math.abs(maxLon - minLon) * fitFactor));
		mapView.getController().animateTo(
				new GeoPoint((maxLat + minLat) / 2, (maxLon + minLon) / 2));
		mapView.invalidate();

		return true;
	}

	/*
	 * Draw route path from currPoint (source) to destination (dest), by calling
	 * googlemaps web service
	 */
	private void drawRoutePath(String destString) {

		// remove all overlays, except first (which should be location markers)
		List<Overlay> listOfOverLays = mapView.getOverlays();
		if (listOfOverLays.size() > 1) {
			for (int i = 0; i < listOfOverLays.size(); i++) {
				if (i != 0)
					listOfOverLays.remove(i);
			}
		}

		// parse dest string, and change all space with '+' character
		String dest = destString.replace(',', ' ');
		dest = dest.replace(' ', '+');
		if (!dest.contains("Montenegro"))
			dest += "+Montenegro";

		Log.i("drawRoutePath", "dest: " + dest);

		// source is defined by public variable currPoint.
		// dest is defined as String!!!
		// connect to map web service
		StringBuilder urlString = new StringBuilder();
		urlString.append("http://maps.google.com/maps?f=d&hl=en");
		urlString.append("&saddr=");// from
		urlString
				.append(Double.toString((double) curPoint.getLatitudeE6() / 1.0E6));
		urlString.append(",");
		urlString
				.append(Double.toString((double) curPoint.getLongitudeE6() / 1.0E6));
		urlString.append("&daddr=");// to
		urlString.append(dest);
		// urlString.append(Double.toString((double) dest.getLatitudeE6() /
		// 1.0E6));
		// urlString.append(",");
		// urlString.append(Double.toString((double) dest.getLongitudeE6() /
		// 1.0E6));
		urlString.append("&ie=UTF8&0&om=0&output=kml");

		Log.d("URL", "URL=" + urlString.toString());

		// get the kml (XML) doc. And parse it to get the coordinates(direction
		// route).
		Document doc = null;
		HttpURLConnection urlConnection = null;
		URL url = null;
		try {
			url = new URL(urlString.toString());
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect();

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream());

			if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {

				List<Overlay> mapOverlays = mapView.getOverlays();
				// obrisi listu overley-a, ako je postojala
				// mapOverlays.clear();
				// reset bounding rectangle of the displayed map
				minLat = Integer.MAX_VALUE;
				maxLat = Integer.MIN_VALUE;
				minLon = Integer.MAX_VALUE;
				maxLon = Integer.MIN_VALUE;

				// String path =
				// doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
				String path = doc.getElementsByTagName("GeometryCollection")
						.item(0).getFirstChild().getFirstChild()
						.getFirstChild().getNodeValue();

				// Log.d("xxx", "path=" + path);

				String[] pairs = path.split(" ");
				String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude,
														// lngLat[1]=latitude,
														// lngLat[2]=height

				// src
				GeoPoint startGP = new GeoPoint(
						(int) (Double.parseDouble(lngLat[1]) * 1E6),
						(int) (Double.parseDouble(lngLat[0]) * 1E6));
				mapOverlays.add(new RouteOverlay(startGP, startGP, Color.RED));

				GeoPoint gp1;
				GeoPoint gp2 = startGP;
				for (int i = 1; i < pairs.length; i++) // the last one would be
														// crash
				{
					lngLat = pairs[i].split(",");
					gp1 = gp2;
					// watch out! For GeoPoint, first:latitude, second:longitude
					gp2 = new GeoPoint(
							(int) (Double.parseDouble(lngLat[1]) * 1E6),
							(int) (Double.parseDouble(lngLat[0]) * 1E6));
					mapOverlays.add(new RouteOverlay(gp1, gp2, 2, Color.BLUE));

					maxLat = Math.max(gp2.getLatitudeE6(), maxLat);
					minLat = Math.min(gp2.getLatitudeE6(), minLat);
					maxLon = Math.max(gp2.getLongitudeE6(), maxLon);
					minLon = Math.min(gp2.getLongitudeE6(), minLon);

					// Log.d("xxx", "pair:" + pairs[i]);

				}
				// mapOverlays.add(new RouteOverlay(dest, dest, 3)); // use the
				// default color
				mapOverlays.add(new RouteOverlay(gp2, gp2, Color.GREEN)); // use
																			// the
																			// default
																			// color

				// make sure all overlays are visible
				double fitFactor = 1.10;
				mapView.getController().zoomToSpan(
						(int) (Math.abs(maxLat - minLat) * fitFactor),
						(int) (Math.abs(maxLon - minLon) * fitFactor));
				mapView.getController().animateTo(
						new GeoPoint((maxLat + minLat) / 2,
								(maxLon + minLon) / 2));
				mapView.invalidate();

			} else {
				Toast.makeText(this, getString(R.string.na_route),
						Toast.LENGTH_LONG).show();
			}
		} catch (MalformedURLException e) {
			// Log.i("drawRoutePath", "MailformedUrlException");
			Toast.makeText(this, getString(R.string.na_route),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (IOException e) {
			// Log.i("drawRoutePath", "IOException");
			Toast.makeText(this, getString(R.string.na_route),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// Log.i("drawRoutePath", "ParserConfigurationException");
			Toast.makeText(this, getString(R.string.na_route),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();

		} catch (SAXException e) {
			// Log.i("drawRoutePath", "SAXException");
			Toast.makeText(this, getString(R.string.na_route),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}

	}

	/*
	 * Draw route path from currPoint (source) to currGpsLocation (dest), by
	 * calling googlemaps web service
	 */
	private void drawRoutePath(Location dest) {

		// remove all overlays, except first (which should be location markers)
		List<Overlay> listOfOverLays = mapView.getOverlays();
		if (listOfOverLays.size() > 1) {
			for (int i = 0; i < listOfOverLays.size(); i++) {
				if (i != 0)
					listOfOverLays.remove(i);
			}
		}

		// source is defined by public variable currPoint.
		// dest is defined as String!!!
		// connect to map web service
		StringBuilder urlString = new StringBuilder();
		urlString.append("http://maps.google.com/maps?f=d&hl=en");
		urlString.append("&saddr=");// from
		urlString
				.append(Double.toString((double) curPoint.getLatitudeE6() / 1.0E6));
		urlString.append(",");
		urlString
				.append(Double.toString((double) curPoint.getLongitudeE6() / 1.0E6));
		urlString.append("&daddr=");// to
		urlString.append(Double.toString(currGpsLocation.getLatitude()));
		urlString.append(",");
		urlString.append(Double.toString(currGpsLocation.getLongitude()));
		// urlString.append(Double.toString((double) dest.getLatitudeE6() /
		// 1.0E6));
		// urlString.append(",");
		// urlString.append(Double.toString((double) dest.getLongitudeE6() /
		// 1.0E6));
		urlString.append("&ie=UTF8&0&om=0&output=kml");

		Log.d("URL", "URL=" + urlString.toString());

		// get the kml (XML) doc. And parse it to get the coordinates(direction
		// route).
		Document doc = null;
		HttpURLConnection urlConnection = null;
		URL url = null;
		try {
			url = new URL(urlString.toString());
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect();

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream());

			if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {

				List<Overlay> mapOverlays = mapView.getOverlays();
				// obrisi listu overley-a, ako je postojala
				// mapOverlays.clear();
				// reset bounding rectangle of the displayed map
				minLat = Integer.MAX_VALUE;
				maxLat = Integer.MIN_VALUE;
				minLon = Integer.MAX_VALUE;
				maxLon = Integer.MIN_VALUE;

				// String path =
				// doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
				String path = doc.getElementsByTagName("GeometryCollection")
						.item(0).getFirstChild().getFirstChild()
						.getFirstChild().getNodeValue();

				// Log.d("xxx", "path=" + path);

				String[] pairs = path.split(" ");
				String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude,
														// lngLat[1]=latitude,
														// lngLat[2]=height

				// src
				GeoPoint startGP = new GeoPoint(
						(int) (Double.parseDouble(lngLat[1]) * 1E6),
						(int) (Double.parseDouble(lngLat[0]) * 1E6));
				mapOverlays.add(new RouteOverlay(startGP, startGP, Color.RED));

				GeoPoint gp1;
				GeoPoint gp2 = startGP;
				for (int i = 1; i < pairs.length; i++) // the last one would be
														// crash
				{
					lngLat = pairs[i].split(",");
					gp1 = gp2;
					// watch out! For GeoPoint, first:latitude, second:longitude
					gp2 = new GeoPoint(
							(int) (Double.parseDouble(lngLat[1]) * 1E6),
							(int) (Double.parseDouble(lngLat[0]) * 1E6));
					mapOverlays.add(new RouteOverlay(gp1, gp2, 2, Color.BLUE));

					maxLat = Math.max(gp2.getLatitudeE6(), maxLat);
					minLat = Math.min(gp2.getLatitudeE6(), minLat);
					maxLon = Math.max(gp2.getLongitudeE6(), maxLon);
					minLon = Math.min(gp2.getLongitudeE6(), minLon);

					// Log.d("xxx", "pair:" + pairs[i]);

				}
				// mapOverlays.add(new RouteOverlay(dest, dest, 3)); // use the
				// default color
				mapOverlays.add(new RouteOverlay(gp2, gp2, Color.GREEN)); // use
																			// the
																			// default
																			// color

				// make sure all overlays are visible
				double fitFactor = 1.10;
				mapView.getController().zoomToSpan(
						(int) (Math.abs(maxLat - minLat) * fitFactor),
						(int) (Math.abs(maxLon - minLon) * fitFactor));
				mapView.getController().animateTo(
						new GeoPoint((maxLat + minLat) / 2,
								(maxLon + minLon) / 2));
				mapView.invalidate();

			} else {
				Toast.makeText(this, getString(R.string.na_route),
						Toast.LENGTH_LONG).show();
			}
		} catch (MalformedURLException e) {
			// Log.i("drawRoutePath", "MailformedUrlException");
			Toast.makeText(this, getString(R.string.na_route),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (IOException e) {
			// Log.i("drawRoutePath", "IOException");
			Toast.makeText(this, getString(R.string.na_route),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// Log.i("drawRoutePath", "ParserConfigurationException");
			Toast.makeText(this, getString(R.string.na_route),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();

		} catch (SAXException e) {
			// Log.i("drawRoutePath", "SAXException");
			Toast.makeText(this, getString(R.string.na_route),
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_CANCELED) {
			// Toast.makeText(this, "activity canceled",
			// Toast.LENGTH_LONG).show();
			Log.i("onActivityResult: - RESULT_CANCELED", "");
		} else if (resultCode == Activity.RESULT_OK) {
			if (requestCode == reqCodeEnum.REQUEST_CODE_LOCINFO.getValue()) {
				String destLocation = data.getStringExtra("destLocation");
				int drawRouteToMyLocation = data.getIntExtra(
						"drawRouteToMyLocation", 1);
				Log.i("OnActivityResult", "destLocation: " + destLocation
						+ ", drawRoute: " + drawRouteToMyLocation);
				if (drawRouteToMyLocation == 1)
					this.drawRoutePath(currGpsLocation);
				else
					this.drawRoutePath(destLocation);
			}
			/*
			 * else if (requestCode ==
			 * reqCodeEnum.POPUP_LIST_CATEGORIES_FOR_ALL_MUNICIPALS.getValue())
			 * { int arrIndex = data.getIntExtra("arrIndex", 0); if (drawMode ==
			 * OnlineMapActivity.mapmodeEnum.DRAW_ALL_MUNICIPALS .getValue()) {
			 * // draw category for all municipals.
			 * this.drawCategoryForMunicipals(arrIndex, 0); } else {
			 * Log.i("onActivityResult",
			 * "Error: unexpected result code or ???"); } } else if (requestCode
			 * ==
			 * reqCodeEnum.POPUP_LIST_CATEGORIES_FOR_ONE_MUNICIPAL.getValue()) {
			 * int arrIndex = data.getIntExtra("arrIndex", 0); if (drawMode ==
			 * OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ONE_MUNICIPAL
			 * .getValue()) { this.drawCategoryForOneMunicipal(arrIndex,
			 * cityId); } else { Log.i("onActivityResult",
			 * "Error: unexpected result code or ???"); } }
			 */
		}
	}

	private void pickupCategory() {
		// pick the category from the dialog
		final String[] items = new String[Category.arrCategory.length];
		// populate array with item names
		for (int i = 0; i < Category.arrCategory.length; i++) {
			if (MainActivity.language == MainActivity.languageEnum.MONTENEGRO
					.getValue())
				items[i] = Category.arrCategory[i].ime;
			else
				items[i] = Category.arrCategory[i].name;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(this.getResources().getText(R.string.select_category));
		builder.setCancelable(true);
		// selectedItem = -1; // must be GLOBAL variable
		builder.setSingleChoiceItems(items, catId,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						dialog.dismiss();
						// drawCategoryForMunicipals(item, 0);
						// call activity f(), based on drawMode
						if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_ALL_MUNICIPALS
								.getValue()) {
							drawCategoryForMunicipals(item, 0);
						} else if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ONE_MUNICIPAL
								.getValue()) {
							drawCategoryForOneMunicipal(item, cityId);
						} else if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ALL_MUNICIPALS
								.getValue()) {
							drawCategoryForMunicipals(item, 0);
						}
					}
				});
		AlertDialog alert = builder.create();
		alert.setCanceledOnTouchOutside(true);
		alert.show();
		alert.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT); // make dialog smaller
														// then
														// activity!????????

	}

	private void pickupMunicipal() {
		// pick the category from the dialog
		final String[] items = new String[Municipal.arrMunicipal.length];
		// populate array with item names
		for (int i = 0; i < Municipal.arrMunicipal.length; i++) {
			items[i] = Municipal.arrMunicipal[i].name;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(this.getResources().getText(R.string.select_municipal));
		builder.setCancelable(true);
		int selectedItem = -1;
		if (cityId > 0)
			selectedItem = cityId - 1;
		builder.setSingleChoiceItems(items, selectedItem,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						dialog.dismiss();
						// call activity f(), based on drawMode
						if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_ALL_MUNICIPALS
								.getValue()) {
							drawCategoryForOneMunicipal(catId, item + 1); // NOTE:
																			// item
																			// is
																			// zero-based!!!
						} else if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ONE_MUNICIPAL
								.getValue()) {
							drawCategoryForOneMunicipal(catId, item + 1); // NOTE:
																			// item
																			// is
																			// zero-based!!!
						} else if (drawMode == OnlineMapActivity.mapmodeEnum.DRAW_CATEGORY_FOR_ALL_MUNICIPALS
								.getValue()) {
							drawCategoryForOneMunicipal(catId, item + 1); // NOTE:
																			// item
																			// is
																			// zero-based!!!
						}
					}
				});
		AlertDialog alert = builder.create();
		alert.setCanceledOnTouchOutside(true);
		alert.show();
		alert.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT); // make dialog smaller
														// then
														// activity!????????

	}

	/*
	 * Following f() is called from CustomItemizedOverlay class, when some
	 * overlay item is Tapped (clicked). Dialog should be opened and asked for
	 * available options
	 */
	public void processInfoDialog(int locID, int catID, int cityID,
			GeoPoint point) {

		// save current location, as we might need it for direction
		locId = locID;
		catId = catID;
		cityId = cityID;

		final int loc_ID = locID;
		final int cat_ID = catID;
		final int city_ID = cityID;

		// Log.i("OnlineMapActivity - processInfoDialog", "Loc: " + locID +
		// ", Cat: " + catID + ", City: " + cityID);
		String name = new String("");
		String city = new String("");
		String url = new String("");
		String phone = "NA";
		String description = new String("");

		/*
		 * If catID == 0, Municipal item was tapped; if catID != 0, one of
		 * category locations was tapped
		 */

		if (catID == Category.categoryEnum.HISTORY.getValue()) {
			city = Municipal.getName(cityID);
			if (MainActivity.language == MainActivity.languageEnum.MONTENEGRO
					.getValue())
				name = HistoryLocation.getIme(locID);
			else
				name = HistoryLocation.getName(locID);
			url = HistoryLocation.getUrl(locID);
			description = HistoryLocation.getDescription(locID);
			// phone = NatureLocation.getPhone(locID);
		} else if (catID == Category.categoryEnum.NATURE.getValue()) {
			city = Municipal.getName(cityID);
			if (MainActivity.language == MainActivity.languageEnum.MONTENEGRO
					.getValue())
				name = NatureLocation.getIme(locID);
			else
				name = NatureLocation.getName(locID);
			url = NatureLocation.getUrl(locID);
			description = NatureLocation.getDescription(locID);
			// phone = NatureLocation.getPhone(locID);
		} else if (catID == Category.categoryEnum.ARCHEOLOGY.getValue()) {
			city = Municipal.getName(cityID);
			if (MainActivity.language == MainActivity.languageEnum.MONTENEGRO
					.getValue())
				name = ArcheologyLocation.getIme(locID);
			else
				name = ArcheologyLocation.getName(locID);
			url = ArcheologyLocation.getUrl(locID);
			// phone = ArcheologyLocation.getPhone(locID);
			description = ArcheologyLocation.getDescription(locID);
		} else if (catID == 0) { // this is municipal
			city = Municipal.getName(cityID);
			name = Municipal.getName(locID);
			url = Municipal.getUrl(locID);
			// phone = Municipal.getPhone(locID);
			description = Municipal.getDescription(locID);
		}

		/*
		 * final String descriptionFileName = description; final String locUrl =
		 * url; final String locPhone = phone; final String locName = name;
		 * final String locCity = city;
		 * 
		 * // custom dialog final Dialog dialog = new Dialog(context);
		 * dialog.setContentView(R.layout.locinfo_dialog);
		 * dialog.setTitle("City: " + city + ", Location: " + name);
		 * 
		 * // set the custom dialog components ImageView iv = (ImageView)
		 * dialog.findViewById(R.id.locinfo_image); //
		 * --------------------------
		 * -------------------->>>>>>>>>>>>>>>>>>>>>>>> String firstPicture =
		 * getFirstPictureFilename(locID, catID, cityID); Drawable d; // if
		 * (firstPicture == "") // d = getDrawableFromPathname("na.png"); //
		 * else d = getDrawableFromPathname(firstPicture);
		 * 
		 * // set background drawable if there is any if (d != null)
		 * iv.setBackgroundDrawable(d);
		 * 
		 * TextView tel = (TextView) dialog.findViewById(R.id.locinfo_tel);
		 * tel.setText(phone);
		 * tel.setMovementMethod(LinkMovementMethod.getInstance());
		 * 
		 * TextView urlLink = (TextView) dialog.findViewById(R.id.locinfo_url);
		 * urlLink.setText(url);
		 * urlLink.setMovementMethod(LinkMovementMethod.getInstance());
		 * 
		 * Button cancelButton = (Button) dialog.findViewById(R.id.cancel_dlg);
		 * // if button is clicked, close the custom dialog
		 * cancelButton.setOnClickListener(new OnClickListener() { public void
		 * onClick(View v) { dialog.dismiss(); } });
		 * 
		 * Button moreinfoButton = (Button) dialog
		 * .findViewById(R.id.locinfo_moreinfo); // if button is clicked, close
		 * the custom dialog moreinfoButton.setOnClickListener(new
		 * OnClickListener() { public void onClick(View v) { dialog.dismiss();
		 * showGallery(loc_ID, cat_ID, city_ID, locName, locCity, locUrl,
		 * locPhone, descriptionFileName); } });
		 * 
		 * Button directionButton = (Button) dialog
		 * .findViewById(R.id.locinfo_direction); // if button is clicked, close
		 * the custom dialog directionButton.setOnClickListener(new
		 * OnClickListener() { public void onClick(View v) { dialog.dismiss(); }
		 * });
		 * 
		 * dialog.show();
		 */
		showGallery(loc_ID, cat_ID, city_ID, point, name, city, url, phone,
				description);
	}

	protected Drawable getDrawableFromPathname(String pathName) {
		Drawable d = null;
		try {
			d = Drawable.createFromStream(getAssets().open(pathName), null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			d = null;
		}
		return d;
	}

	private String getFirstPictureFilename(int locID, int catID, int cityID) {

		String name = "";
		for (int i = 0; i < GalleryInfo.arrGallery.length; i++) {
			if (locID == GalleryInfo.arrGallery[i].locID
					&& catID == GalleryInfo.arrGallery[i].catID
					&& cityID == GalleryInfo.arrGallery[i].cityID) {
				if (GalleryInfo.arrGallery[i].imageName.endsWith("/"))
					return "";
				else
					return GalleryInfo.arrGallery[i].imageName;
			}
		}
		return name;
	}

	private void showGallery(int locID, int catID, int cityID, GeoPoint point,
			String name, String city, String url, String phone,
			String locDescription) {

		// save current geopoint
		curPoint = point;

		ArrayList<String> imageNamesArrList = new ArrayList<String>();
		ArrayList<String> imageUrlsArrList = new ArrayList<String>();

		// populate array with item names
		for (int i = 0; i < GalleryInfo.arrGallery.length; i++) {
			if (locID == GalleryInfo.arrGallery[i].locID
					&& catID == GalleryInfo.arrGallery[i].catID
					&& cityID == GalleryInfo.arrGallery[i].cityID) {
				if (GalleryInfo.arrGallery[i].imageName.endsWith("/") == false) {
					imageNamesArrList.add(GalleryInfo.arrGallery[i].imageName);
					imageUrlsArrList.add(GalleryInfo.arrGallery[i].imageUrl);
					// Log.i("OnlineMapActivity - showGallery",
					// "Ucitana slika: " + GalleryInfo.arrGallery[i].imageName +
					// ", Url: " + GalleryInfo.arrGallery[i].imageUrl);
				}
			}
		}
		// Log.i("OnlineMapActivity - showGallery", "filenameArrList length: " +
		// filenameArrList.size());

		Intent i = new Intent(getApplicationContext(),
				LocationInfoActivity.class);
		i.putStringArrayListExtra("imageNamesArr", imageNamesArrList);
		i.putStringArrayListExtra("imageUrlsArr", imageUrlsArrList);

		// get info about location and pass to new activity
		String description = "";

		if (locDescription.endsWith("/") == true) {
			if (url.equals(null) || url.equals("")) {
				description = "\r\n" + name + ", " + city;
			} else {
				description = "\r\n" + name + ", " + city + "\r\n\r\n"
						+ getBaseContext().getString(R.string.more_details)
						+ url;
			}
		} else
			description = "\r\n" + name + ", " + city + "\r\n\r\n"
					+ getLocationDescription(locDescription);

		// Log.i("Pozivam getLocationDescription", "locDescription: " +
		// description);

		i.putExtra("locDescription", description);

		i.putExtra("name", name);
		i.putExtra("city", city);
		i.putExtra("url", url);
		i.putExtra("phoneNumber", phone);
		// Log.i("Pozivam showGallery", "name: " + name + ", description: " +
		// description);

		// startActivity(i);
		startActivityForResult(i,
				OnlineMapActivity.reqCodeEnum.REQUEST_CODE_LOCINFO.getValue());

		/*
		 * Sledeci dio koda, poziva novi activity, prosledjuje parametre i onda
		 * ceka na rezultat
		 */
		// REQUEST_CODE treba da posluzi da razlikujemo koji Activity je vratio
		// rezultat!!!
		// startActivityForResult(i, REQUEST_CODE);

	}

	/*
	 * get desription about location from XML file
	 */
	private String getLocationDescription(String locDescription) {
		String description = null;
		LocDescriptionFileParser parser = new LocDescriptionFileParser();
		List<LocDescriptionFile> locDescriptionArray = parser.readLocation(
				getAssets(), locDescription);

		if (locDescriptionArray == null) {
			description = getBaseContext().getString(R.string.na_info);
		} else {
			if (MainActivity.language == MainActivity.languageEnum.MONTENEGRO
					.getValue()) {
				if (locDescriptionArray.size() == 0) {
					description = getString(R.string.na_info);
				} else {
					description = locDescriptionArray.get(0).text_mne;
				}
			} else {
				if (locDescriptionArray.size() == 0) {
					description = getString(R.string.na_info);
				} else {
					description = locDescriptionArray.get(0).text_eng;
				}
			}
		}

		return description;
	}

	private void handleLongressListener(GeoPoint loc) {
		/*
		 * here is a tricky staff: if we want to avoid
		 * CustomItemizedOverlay.OnTap, which is going to happen after
		 * Longpreess event (OnTouch event), then we need to return true from
		 * the OnTouch event. To do that, we'll set here some protected flag of
		 * MyCustomMapView class, and then, in MyCustomMapView.OnTouch, we'll
		 * reset that flag and return true!!!
		 */
		// Log.i("OnLineMapActivity", "handleLongpressListener");
		this.mapView.longpressExecuted = 1;

		gpsSetCurrentLocation(loc);

	}

	public void gpsSetCurrentLocation(GeoPoint loc) {
		// Log.i("handleLongpressListener", "My new location: " +
		// loc.getLatitudeE6() / 1E6 + "," + loc.getLongitudeE6() /1E6);

		// locLstnr.gpsDrawCurrentLocationMarker("" + loc.getLatitudeE6() / 1E6,
		// "" + loc.getLongitudeE6() / 1E6);
		String coordinates[] = { "" + loc.getLatitudeE6() / 1E6,
				"" + loc.getLongitudeE6() / 1E6 };

		// if location is different from current location, and within
		// Montenegro, change current Location
		if (isLocationWithinMontenegro(coordinates[0], coordinates[1])) {

			if ((currGpsLocation.getLatitude() != (loc.getLatitudeE6() / 1E6))
					&& (currGpsLocation.getLongitude() != (loc.getLongitudeE6() / 1E6))) {
				currGpsLocation.setLatitude(loc.getLatitudeE6() / 1E6);
				currGpsLocation.setLongitude(loc.getLongitudeE6() / 1E6);
				String Text = getString(R.string.current_location_changed)
						+ "Latitude = " + currGpsLocation.getLatitude()
						+ "Longitude = " + currGpsLocation.getLongitude();
				Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_LONG)
						.show();
				gpsDrawCurrentLocationMarker(coordinates[0], coordinates[1]);
				// Log.i("gpsSetCurrentLocation", Text);
			}
		} else {
			Toast.makeText(getApplicationContext(),
					getString(R.string.current_location_change_note),
					Toast.LENGTH_LONG).show();
		}

	}

	public void gpsDrawCurrentLocationMarker(String latitude, String longitude) {

		double lat = Double.parseDouble(latitude);
		double lng = Double.parseDouble(longitude);

		GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

		// mc.animateTo(p);
		// mc.setZoom(18);

		CurrentLocationOverlays marker = new CurrentLocationOverlays(p);
		List<Overlay> listOfOverLays = mapView.getOverlays();

		if (listOfOverLays.size() > 1) {

			for (int i = 0; i < listOfOverLays.size(); i++) {
				if (i != 0)
					listOfOverLays.remove(i);
			}
		}

		listOfOverLays.add(marker);
		mapView.invalidate();

	}

	public boolean isLocationWithinMontenegro(String loc_lat, String loc_long) {

		int cityID = mcp.getCityIdForGpsCoordinate(Double.parseDouble(loc_lat),
				Double.parseDouble(loc_long));
		if (cityID != -1)
			return true;
		else
			return false;
	}

	public void ZoomToCurrentLocation() {

		double lat = currGpsLocation.getLatitude();
		double lng = currGpsLocation.getLongitude();

		GeoPoint p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

		mc.animateTo(p);
		mc.setZoom(18);

		CurrentLocationOverlays marker = new CurrentLocationOverlays(p);
		List<Overlay> listOfOverLays = mapView.getOverlays();

		if (listOfOverLays.size() > 1) {

			for (int i = 0; i < listOfOverLays.size(); i++) {
				if (i != 0)
					listOfOverLays.remove(i);
			}
		}

		listOfOverLays.add(marker);
		mapView.invalidate();
	}

	public class MyLocationListener implements LocationListener {

		public void onLocationChanged(Location loc) {

			String coordinates[] = { "" + loc.getLatitude(),
					"" + loc.getLongitude() };

			// if location is different from current location, and within
			// Montenegro, change current Location
			if (isLocationWithinMontenegro(coordinates[0], coordinates[1])) {

				if (currGpsLocation.getLatitude() != loc.getLatitude()
						&& currGpsLocation.getLongitude() != loc.getLongitude()) {
					currGpsLocation.setLatitude(loc.getLatitude());
					currGpsLocation.setLongitude(loc.getLongitude());
					gpsDrawCurrentLocationMarker(coordinates[0], coordinates[1]);
					String Text = getString(R.string.current_location_changed_by_gps)
							+ "Latitude = "
							+ loc.getLatitude()
							+ "Longitude = " + loc.getLongitude();
					Toast.makeText(getApplicationContext(), Text,
							Toast.LENGTH_LONG).show();
				}
			}
		}

		public void onProviderDisabled(String provider) {
			// Toast.makeText(getApplicationContext(), "Gps Disabled",
			// Toast.LENGTH_LONG).show();
			gpsProviderEnabled = false;
			// Log.i("onProviderDisabled",
			// getString(R.string.gps_provider_disabled));
		}

		public void onProviderEnabled(String provider) {
			// Toast.makeText(getApplicationContext(), "Gps Enabled",
			// Toast.LENGTH_LONG).show();
			gpsProviderEnabled = true;
			// Log.i("onProviderEnabled",
			// getString(R.string.gps_provider_enabled));
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {

		}

	}

	/* My overlay Class starts */
	class CurrentLocationOverlays extends com.google.android.maps.Overlay {
		GeoPoint location = null;

		public CurrentLocationOverlays(final GeoPoint location) {
			super();
			this.location = location;
		}

		@Override
		public void draw(final Canvas canvas, final MapView mapView,
				final boolean shadow) {

			super.draw(canvas, mapView, shadow);
			// translate the screen pixels
			final Point screenPoint = new Point();
			mapView.getProjection().toPixels(this.location, screenPoint);

			// add the image
			canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),
					R.drawable.ic_delete), screenPoint.x, screenPoint.y, null); // Setting
																				// the
																				// image
																				// &nbsp;location
																				// on
																				// the
																				// screen
																				// (x,y).
			// canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),
			// R.drawable.mylocation1), screenPoint.x, screenPoint.y , null);
			// //Setting the image &nbsp;location on the screen (x,y).
		}

		/*
		 * @Override public boolean onTouchEvent(MotionEvent event, MapView
		 * mapView) { //---when user lifts his finger--- if (event.getAction()
		 * == 1) { GeoPoint p = mapView.getProjection().fromPixels((int)
		 * event.getX(), (int) event.getY());
		 * 
		 * // Toast.makeText(getBaseContext(), "Adr: " + p.getLatitudeE6() / 1E6
		 * + "," + p.getLongitudeE6() /1E6 , Toast.LENGTH_LONG).show();
		 * Log.i("CurrentLocationOverlays - onTouchEvent", "Adr: " +
		 * p.getLatitudeE6() / 1E6 + "," + p.getLongitudeE6() /1E6);
		 * 
		 * locLstnr.gpsSetCurrentLocation("" + p.getLatitudeE6() / 1E6, "" +
		 * p.getLongitudeE6() /1E6);
		 * 
		 * Geocoder geoCoder = new Geocoder(getBaseContext(),
		 * Locale.getDefault()); try { List<Address> addresses =
		 * geoCoder.getFromLocation( p.getLatitudeE6() / 1E6, p.getLongitudeE6()
		 * / 1E6, 1);
		 * 
		 * String add = "Adresa: "; if (addresses.size() > 0) { for (int i=0;
		 * i<addresses.get(0).getMaxAddressLineIndex(); i++) add +=
		 * addresses.get(0).getAddressLine(i) + "\n"; }
		 * 
		 * Toast.makeText(getBaseContext(), add, Toast.LENGTH_LONG).show(); }
		 * catch (IOException e) { //Toast.makeText(getBaseContext(), "Greska!",
		 * Toast.LENGTH_LONG).show(); e.printStackTrace(); }
		 * 
		 * return true; } else return false; }
		 */
	}
	/* My overlay Class ends */

}
